package gold.digger;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC03 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution_fail {
        public int lengthOfLongestSubstring(String s) {
            int len = s.length();
            Map<Character, Integer> map = new HashMap<>();
            int maxLen = 0;
            int curStart = -1;

            for (int i = 0; i < len; i++) {
                char cur = s.charAt(i);
                if (map.containsKey(cur)) {
                    curStart = map.get(cur) > curStart ? map.get(cur) : curStart;
                    int curLen = i - curStart;
                    maxLen = Math.max(maxLen, curLen);
                    curStart = i - 1;
                } else {
                    int curLen = i - curStart;
                    maxLen = Math.max(maxLen, curLen);
                }

                map.put(cur, i);
            }

            return maxLen;
        }
    }

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            // 哈希集合，记录每个字符是否出现过
            Set<Character> occ = new HashSet<Character>();
            int n = s.length();
            // 右指针，初始值为 -1，相当于我们在字符串的左边界的左侧，还没有开始移动
            int rk = -1, ans = 0;
            for (int i = 0; i < n; ++i) {
                if (i != 0) {
                    // 左指针向右移动一格，移除一个字符
                    occ.remove(s.charAt(i - 1));
                }
                while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) {
                    // 不断地移动右指针
                    occ.add(s.charAt(rk + 1));
                    ++rk;
                }
                // 第 i 到 rk 个字符是一个极长的无重复字符子串
                ans = Math.max(ans, rk - i + 1);
            }
            return ans;
        }
    }


    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.lengthOfLongestSubstring("dvdf"));
    }

    public static void main(String[] args) throws Exception {
        LC03 an = new LC03();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
